<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form ref="formRef" class="ls-form" label-width="140px" :rules="rules" :model="formData">
                <div class="xl:flex flex-row" style="flex-wrap: wrap;">
                    <template v-for="(item, index) in columnArr.column" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name">
                            <div class="w-80">
                                <!-- 日期选择器 -->
                                <div v-if="datePicker.indexOf(item.column_name) != -1">
                                    <!-- <el-date-picker v-model="formData[item.column_name]" format="yyyy 年 MM 月 dd 日"  type="date"
                                        placeholder="请选择日期" style="width: 100%;height: 40px;;" /> -->
                                    <el-date-picker v-model="formData[item.column_name]" type="date" placeholder="选择日期"
                                        format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;;">
                                    </el-date-picker>
                                </div>
                                <!-- 枚举类型 -->
                                <div v-else-if="enumerate.indexOf(item.column_name) != -1">
                                    <el-select v-model="formData[item.column_name]" :data-index="index" placeholder="请选择"
                                        size="large" style="width: 100%;">
                                        <el-option
                                            v-for="(item1, index1) in dictOptions.options[item.column_name]['options']"
                                            :label="item1.name" :value="item1.value" />
                                    </el-select>
                                </div>
                                <!-- 普通select -->
                                <div v-else-if="select.indexOf(item.column_name) != -1">
                                    <el-select v-model="formData[item.column_name]" :data-index="index" placeholder="请选择"
                                        size="large" style="width: 100%;">
                                        <el-option v-for="(item1, index1) in admin.options" :label="item1.name"
                                            :value="item1.id" />
                                    </el-select>
                                </div>
                                <!-- 部门 -->
                                <div v-else-if="item.column_name == 'dept_id'">
                                    <el-select v-model="formData[item.column_name]" :data-index="index" placeholder="请选择"
                                        size="large" style="width: 100%;">
                                        <el-option v-for="(item1, index1) in deptOptions.options" :label="item1.name"
                                            :value="item1.id" />
                                    </el-select>
                                </div>

                                <div v-else-if="item.column_name == 'img'">
                                    <el-upload :file-list="formData[item.column_name]" ref="upload" class="upload-demo"
                                        :action="action" :show-file-list="true" :headers="headers"
                                        :on-success="handleSuccess" list-type="picture">
                                        <el-button type="primary">本地上传</el-button>
                                    </el-upload>
                                    <!-- <el-upload class="upload-demo" :action="action" :headers="headers"
                                        :on-success="handleSuccess" :on-remove="handleRemove" multiple
                                        :on-exceed="handleExceed" :file-list="formData[item.cacolumn_name]">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                                    </el-upload> -->
                                </div>
                                <div v-else-if="typeNumer.indexOf(item.column_name) != -1">
                                    <el-space>
                                    <el-input-number 
                                    v-model="formData[item.column_name]" 
                                    :min="0" 
                                    :max="100000000"
                                    style="width: 100%;height: 40px;;"
                                    >
                                    <template #prefix>
                                        <span>￥</span>
                                    </template>
                                    </el-input-number>
                                </el-space>
                                </div>
                                <div v-else>
                                    <el-input v-model="formData[item.column_name]" :placeholder="'请输入' + item.name"
                                        type="data" show-word-limit clearable style="width: 100%;height: 40px;;" />
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="articleListsEdit">
import type { FormInstance } from 'element-plus'
import config from '@/config'

import { getColumn, getDict } from '@/api/perms/role'
import { inforAdd } from '@/api/information/information'

import { adminAll } from '@/api/perms/admin'
import { deptAll } from '@/api/org/department'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId } from 'element-plus'
import feedback from '@/utils/feedback'
const formRef = shallowRef<FormInstance>()

const upload = ref<UploadInstance>()

// import RelationsAdd from '../components/relations-add.vue'
const userStore = useUserStore()
const appStore = useAppStore()
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
console.log(action.value, "action")
const headers = computed(() => ({
    token: userStore.token,
    version: appStore.config.version
}))
const route = useRoute()
const router = useRouter()
const formData = reactive({});
//日期
let datePicker = [
    'first_commit_time',
    'update_paper_time',
    'commit_time'
];
//枚举值
let enumerate = [
    'is_settlement',
    'is_degree',
    'hosting',
    'status',
    'dept_status',
    'charge_of_group',
    'belong_dept',
    'have_title',
    'pre_material_state',
    'is_duplicate_checking',
];
//下拉选择
let select = [
    'admin_id',
    'principal',
    'receiver_id',
    'after_sale_id',
];

let typeNumer = [
    'total_amount',
    'initial_payment',
    'balance_payment',
    'paper_number',
];
const columnArr = reactive({
    "column": []
})
const { removeTab } = useMultipleTabs()
const rules = reactive({
    dept_id: [
        { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    number: [
        { required: true, message: '请输入编号', trigger: 'blur' }
    ],
    wechat_name: [
        { required: true, message: '请输入微信名称', trigger: 'blur' }
    ],
    total_amount: [
        { required: true, message: '请输入总金额', trigger: 'blur' },
        { type: 'number', message: '总计金额必须为数字',trigger: 'blur' },
    ],
    initial_payment: [
        { required: true, message: '请输入首付款', trigger: 'blur' },
        { type: 'number', message: '首付款必须为数字',trigger: 'blur' },
    ],
    balance_payment: [
        { required: true, message: '请输入尾款', trigger: 'blur' },
        { type: 'number', message: '尾款必须为数字', trigger: 'blur'},
    ],
    agent_name: [
        { required: true, message: '请输入中介名称', trigger: 'blur' }
    ],
    school_name: [
        { required: true, message: '请输入学校名称', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    professional_name: [
        { required: true, message: '请输入专业名称', trigger: 'blur' }
    ],
    is_degree: [
        { required: true, message: '请选择学位', trigger: 'change' }
    ],
    topic_service: [
        { required: true, message: '请输入题目业务', trigger: 'blur' }
    ],
    paper_number: [
        { required: true, message: '请输入字数', trigger: 'blur' },
        { type: 'number', message: '字数为数字' },
    ],
    duplicate_checking: [
        { required: true, message: '请输入查重', trigger: 'blur' }
    ],
    duplicate_checking_system: [
        { required: true, message: '请输入查重系统', trigger: 'blur' }
    ],
    submission_material: [
        { required: true, message: '请输入交稿材料', trigger: 'blur' }
    ],
    first_commit_time: [
        { required: true, message: '请输入交稿时间', trigger: 'change' }
    ],
    commit_time: [
        { required: true, message: '请输入应交时间', trigger: 'change' }
    ],
})
const dictOptions = reactive({
    options: {},
})
const admin = reactive({
    options: [],
});
const deptOptions = reactive({
    options: [],
});
const getColumns = async () => {
    let columnAuth = await getColumn()
    let dict = await getDict();
    admin.options = await adminAll();
    let dept = await deptAll();
    deptOptions.options = dept[0]['children'];

    //整理枚举类型字典数组
    dict.forEach(element => {
        dictOptions.options[element.type] = element;
    })
    columnAuth.column.forEach(element => {
        if (element.radio == 1) {
            if (element.column_name != 'img') {
                formData[element.column_name] = "";
            } else {
                formData[element.column_name] = [];
            }
            columnArr.column.push(element);
        }
    });
    console.log(formData);
}
const handleExceed: UploadProps['onExceed'] = (files) => {

    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const handleSuccess = (event: any, file: any) => {
    console.log(event, file, "handleSuccess")
    if (event.show == 1) {
        feedback.msgError(`${file.name}文件上传失败`)
    } else {
        formData['img'].push(event.data.id);
        console.log(formData['img']);
    }
}
const handleRemove = (event: any, file: any) => {
    console.log(event);
    formData['img'].splice(formData['img'].indexOf(event.response.data.id), 1);
}
const onSubmit = async () => {
    try {
        await formRef.value?.validate()
        let submitData = {};
        Object.keys(formData).forEach((key) => {
            //@ts-ignore
            if (datePicker.indexOf(key) != -1) {
                submitData[key] = formData[key] / 1000;
            } else {
                submitData[key] = formData[key];
            }
        });
        console.log(submitData);
        await inforAdd(submitData)

        removeTab()
        router.back()
    } catch (error: any) {
        for (const err in error) {
            const isInRules = Object.keys(rules).includes(err)
            isInRules && feedback.msgError(error[err][0]?.message)
        }
    }
}
getColumns();
</script>
